import { makeObservable, observable, action, computed, runInAction } from "mobx";
import { BaseStore } from "../BaseStore";
import type { User, AuthState } from "./index.d";
import { RootStore } from "../RootStore";

export class UserStore extends BaseStore {
  authState: AuthState = {
    isAuthenticated: false,
    user: null,
    token: null,
  };

  users: User[] = [];

  constructor(private rootStore: RootStore) {
    super();
    makeObservable(this, {
      authState: observable,
      users: observable,
      currentUser: computed,
      isLoggedIn: computed,
      login: action,
      logout: action,
      register: action,
      updateProfile: action,
      fetchUsers: action,
    });
  }

  // Computed values
  get currentUser(): User | null {
    return this.authState.user;
  }

  get isLoggedIn(): boolean {
    return this.authState.isAuthenticated;
  }

  // Actions
  login = async (email: string, password: string): Promise<boolean> => {
    console.log(this.rootStore)
    return (
      (await this.executeAsync(async () => {
        // 模拟登录 API 调用
        await new Promise((resolve) => setTimeout(resolve, 1000));

        const user: User = {
          id: "1",
          name: "John Doe",
          email: email,
          createdAt: new Date(),
        };

        runInAction(() => {
          this.authState = {
            isAuthenticated: true,
            user,
            token: "mock-jwt-token",
          };
        });

        return true;
      })) !== null
    );
  };

  logout = (): void => {
    this.authState = {
      isAuthenticated: false,
      user: null,
      token: null,
    };
  };

  register = async (
    name: string,
    email: string,
    password: string
  ): Promise<boolean> => {
    return (
      (await this.executeAsync(async () => {
        // 模拟注册 API 调用
        await new Promise((resolve) => setTimeout(resolve, 1000));

        const newUser: User = {
          id: Math.random().toString(36).substr(2, 9),
          name,
          email,
          password,
          createdAt: new Date(),
        };

        this.users.push(newUser);

        // 自动登录
        this.authState = {
          isAuthenticated: true,
          user: newUser,
          token: "mock-jwt-token",
        };

        return true;
      })) !== null
    );
  };

  updateProfile = async (updates: Partial<User>): Promise<void> => {
    await this.executeAsync(async () => {
      if (this.authState.user) {
        this.authState.user = {
          ...this.authState.user,
          ...updates,
        };
      }
    });
  };

  fetchUsers = async (): Promise<void> => {
    await this.executeAsync(async () => {
      // 模拟获取用户列表 API
      await new Promise((resolve) => setTimeout(resolve, 500));

      this.users = [
        {
          id: "1",
          name: "John Doe",
          email: "john@example.com",
          createdAt: new Date("2023-01-01"),
        },
        {
          id: "2",
          name: "Jane Smith",
          email: "jane@example.com",
          createdAt: new Date("2023-01-02"),
        },
      ];
    });
  };
}
